package de.szut.main;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import de.szut.database.DatabaseHelper;
import de.szut.dynamic.view.AbilityTreeGenerator;
import de.szut.entity.Country;
import de.szut.entity.Points;
import de.szut.fragments.WorldMenuGenerator;
import de.szut.interfaces.IResearch;
import de.szut.logic.Logic;
import de.szut.logic.ModifierStore;
import de.szut.scene.helper.GameMapHelper;
import de.szut.scene.helper.SceneManager;
import de.szut.scene.helper.StorageHelper;
import de.szut.scene.scenes.GameScene;
import de.szut.util.ModifierType;
import de.szut.util.Settings;
import de.szut.xml.AbilityXmlParser;
import de.szut.xml.CountryXmlParser;
import org.andengine.engine.Engine;
import org.andengine.engine.LimitedFPSEngine;
import org.andengine.engine.camera.ZoomCamera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.input.touch.controller.MultiTouch;
import org.andengine.input.touch.controller.MultiTouchController;
import org.andengine.opengl.view.RenderSurfaceView;
import org.andengine.ui.activity.BaseGameActivity;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

/**
 * Created by dzebcuks on 22.08.13.
 */
public class GameActivity extends BaseGameActivity {

    private ZoomCamera zoomCamera;
    private ResourcesManager resourcesManager;
    private FragmentManager fragmentManager;
    private GameMapHelper gameMapHelper;
    private DatabaseHelper dbHelper;
    private StorageHelper storageHelper;
    private ModifierStore modifierStore;
    private View abilityMenu;
    private View worldMenu;
    private AbilityTreeGenerator abilityGenerator;
    private WorldMenuGenerator worldMenuGenerator;

    @Override
    public EngineOptions onCreateEngineOptions() {
        zoomCamera = new ZoomCamera(0, 0, Settings.RESOLUTION_WIDTH, Settings.RESOLUTION_HEIGHT);
        EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED,
                new FillResolutionPolicy(),
                this.zoomCamera);
        engineOptions.getAudioOptions().setNeedsMusic(false).setNeedsSound(false);
        engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
        engineOptions.getRenderOptions().setDithering(true);
        return engineOptions;
    }

    @Override
    public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws
            IOException {
        dbHelper = DatabaseHelper.getInstance(this);
        storageHelper = StorageHelper.getInstance(this,dbHelper);
        gameMapHelper = GameMapHelper.getInctance();
        fragmentManager = this.getSupportFragmentManager();
        ResourcesManager.prepareManager(mEngine, this, this.zoomCamera, getVertexBufferObjectManager(), fragmentManager, gameMapHelper, dbHelper,storageHelper);
        this.resourcesManager = ResourcesManager.getInstance();
        pOnCreateResourcesCallback.onCreateResourcesFinished();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        SceneManager sceneManager = SceneManager.getInstance();
        if (sceneManager.getCurrentScene() instanceof GameScene) {
            if (((GameScene) sceneManager.getCurrentScene()).isTimeIsRunning()) {
                ((GameScene) sceneManager.getCurrentScene()).pauseTimer();
                Logic logic = Logic.getInstance(this);
                outState.putSerializable(Settings.BUNDLE_MODIFIER_VALUES, logic.getModifierValues());
                outState.putSerializable(Settings.BUNDLE_INFECTED_COUNTRIES, (Serializable) logic.getInfectedCountries());
                outState.putSerializable(Settings.BUNDLE_NON_INFECTED_COUNTRIES, (Serializable) logic.getNonInfectedCountries());
                outState.putSerializable(Settings.BUNDLE_RESEARCHES, (Serializable) logic.getResearches());
                outState.putSerializable(Settings.BUNDLE_CONTROLLED_COUNTRIES, (Serializable) logic.getControlledCountries());
            }
        }
        super.onSaveInstanceState(outState);    //To change body of overridden methods use File | Settings | File Templates.
    }

    @Override
    protected void onCreate(Bundle pSavedInstanceState) {
        super.onCreate(pSavedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.
        if (pSavedInstanceState != null) {
            SceneManager sceneManager = SceneManager.getInstance();
            if (sceneManager.getCurrentScene() instanceof GameScene) {
                if (((GameScene) sceneManager.getCurrentScene()).isTimeIsRunning() == false) {
                    ((GameScene) sceneManager.getCurrentScene()).reRunTimer();

                    Logic logic = Logic.getInstance(this);
//            if (pSavedInstanceState.getSerializable(Settings.BUNDLE_LOGIC_KEY) != null) {
//                Logic.setInstance((Logic) pSavedInstanceState.getSerializable(Settings.BUNDLE_LOGIC_KEY));
//            }
                    if (pSavedInstanceState.getSerializable(Settings.BUNDLE_MODIFIER_VALUES) != null) {
                        logic.setModifierValues((HashMap<ModifierType, Double>) pSavedInstanceState.getSerializable(Settings.BUNDLE_MODIFIER_VALUES));
                    }
                    if (pSavedInstanceState.getSerializable(Settings.BUNDLE_INFECTED_COUNTRIES) != null) {
                        logic.setInfectedCountries((List<Country>) pSavedInstanceState.getSerializable(Settings.BUNDLE_INFECTED_COUNTRIES));
                    }
                    if (pSavedInstanceState.getSerializable(Settings.BUNDLE_NON_INFECTED_COUNTRIES) != null) {
                        logic.setNonInfectedCountries((List<Country>) pSavedInstanceState.getSerializable(Settings.BUNDLE_NON_INFECTED_COUNTRIES));
                    }
                    if (pSavedInstanceState.getSerializable(Settings.BUNDLE_RESEARCHES) != null) {
                        logic.setResearches((List<IResearch>) pSavedInstanceState.getSerializable(Settings.BUNDLE_RESEARCHES));
                    }
                    if (pSavedInstanceState.getSerializable(Settings.BUNDLE_CONTROLLED_COUNTRIES) != null) {
                        logic.setControlledCountries((List<Country>) pSavedInstanceState.getSerializable(Settings.BUNDLE_CONTROLLED_COUNTRIES));
                    }
                }
            }
        }
    }

    @Override
    public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException {
        SceneManager.getInstance().createSplashScene(pOnCreateSceneCallback);

    }

    @Override
    public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback)
            throws IOException {
        mEngine.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback() {
            public void onTimePassed(final TimerHandler pTimerHandler) {
                mEngine.unregisterUpdateHandler(pTimerHandler);
                checkInitiate();
                SceneManager.getInstance().createMenuScene();
            }
        }));
        pOnPopulateSceneCallback.onPopulateSceneFinished();
    }

    @Override
    public Engine onCreateEngine(EngineOptions pEngineOptions) {
        LimitedFPSEngine engine = new LimitedFPSEngine(pEngineOptions, 60);
        if (MultiTouch.isSupported(this)) {
            engine.setTouchController(new MultiTouchController());
        }
        return new LimitedFPSEngine(pEngineOptions, 60);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
        }
        return false;
    }

    private boolean isFirstAppStart() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        boolean firstStart = prefs.getBoolean(Settings.KEY_FIRST_APP_START, true);
        return firstStart;
    }

    private void saveSuccessfulStart() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().putBoolean(Settings.KEY_FIRST_APP_START, false).commit();
    }

    public void checkInitiate() {
        if (this.isFirstAppStart()) {
            try {
                Points points = new Points();
                dbHelper.getPointsDao().insertPoints(points);
                AbilityXmlParser abilityXmlParser = new AbilityXmlParser();
                CountryXmlParser countryXmlParser = new CountryXmlParser();
                List<Object> countries = countryXmlParser.parse(this.getResources()
                        .getAssets().open(Settings.XML_COUNTRY_FILENAME));
                List<Object> abilities = abilityXmlParser.parse(this.getResources()
                        .getAssets()
                        .open(Settings
                                .XML_ABILITY_FILENAME));
                this.modifierStore = Logic.getInstance(this).getModifierStore();
                this.modifierStore.initiateDatabase(abilities, countries);
                this.saveSuccessfulStart();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onSetContentView() {
        this.abilityGenerator = new AbilityTreeGenerator(this);
        this.worldMenuGenerator = new WorldMenuGenerator(this, this);
        this.worldMenu = worldMenuGenerator.generate();
        this.abilityMenu = abilityGenerator.generate();
        this.abilityMenu.setVisibility(View.GONE);
        this.worldMenu.setVisibility(View.GONE);
        this.mRenderSurfaceView = new RenderSurfaceView(this);
        this.mRenderSurfaceView.setRenderer(this.mEngine, this);
        final android.widget.FrameLayout.LayoutParams surfaceViewLayoutParams = new FrameLayout.LayoutParams(super.createSurfaceViewLayoutParams());
        final FrameLayout.LayoutParams adViewLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
        final FrameLayout frameLayout = new FrameLayout(this);
        final FrameLayout.LayoutParams frameLayoutLayoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
        frameLayout.addView(this.mRenderSurfaceView, surfaceViewLayoutParams);
        frameLayout.addView(abilityMenu, adViewLayoutParams);
        frameLayout.addView(worldMenu, adViewLayoutParams);
        this.setContentView(frameLayout, frameLayoutLayoutParams);
    }

    public View getWorldMenu() {
        return worldMenu;
    }

    public View getAbilityMenu() {
        return abilityMenu;
    }

    public WorldMenuGenerator getWorldMenuGenerator() {
        return worldMenuGenerator;
    }


}
